﻿<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增进货订单</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        .container {
            width: 95%;
            margin: 20px auto;
        }

        .form-group {
            margin-bottom: 20px;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .form-item {
            margin-bottom: 16px;
        }

        .note-input {
            height: 100px;
        }

        .upload-area {
            margin-top: 20px;
        }

        .custom-unit-select {
            min-width: 120px; /* 单位下拉框宽度 */
        }

        .tip {
            margin-top: 8px;
            color: #606266;
            font-size: 12px;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 基础信息 -->
        <div class="form-group">
            <h3>基础信息</h3>
            <el-form label-width="120px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="进货单号" required class="form-item">
                            <el-input placeholder="自动获取系统编号" v-model="formData.purchase_order_no" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="进货日期" required class="form-item">
                            <el-date-picker v-model="formData.purchase_date" type="date" style="width: 505px;" placeholder="请选择"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="供应商" required class="form-item">
                            <el-select v-model="formData.supplier_id"
                                       placeholder="请选择"
                                       v-on:change="handleSupplierChange">
                                <el-option v-for="item in supplierOptions"
                                           :key="item.id"
                                           :label="item.name"
                                           :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系人" class="form-item">
                            <el-input v-model="formData.contact_person" placeholder="请选择供应商" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="联系方式" class="form-item">
                            <el-input v-model="formData.contact_information" placeholder="请选择供应商" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="进货部门" required class="form-item">
                            <el-select v-model="formData.purchasing_department" placeholder="请选择">
                                <el-option label="采购部" value="采购部"></el-option>
                                <el-option label="仓储部" value="仓储部"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="进货人" required class="form-item">
                            <el-select v-model="formData.purchaser" placeholder="请选择">
                                <el-option label="李华" value="李华"></el-option>
                                <el-option label="张德衰" value="张德衰"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" class="form-item">
                            <el-input v-model="formData.note" type="textarea" placeholder="请输入" class="note-input"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 进货明细 -->
        <div class="form-group">
            <h3>进货明细</h3>
            <el-row>
                <el-col :span="12">
                    <el-button type="primary" v-on:click="openGoodsDialog">新增</el-button>
                    <el-button v-on:click="removeGoodsRow">移除</el-button>
                </el-col>
            </el-row>
            <el-table :data="tableData" style="width: 100%; margin-top: 16px;">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="product_name" label="货品名称" width="120"></el-table-column>
                <el-table-column prop="product_code" label="货品编号" width="120"></el-table-column>
                <el-table-column prop="specification_model" label="规格型号" width="100"></el-table-column>
                <el-table-column prop="unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="type_of_goods" label="货品类型" width="100"></el-table-column>
                <el-table-column prop="current_inventory" label="当前库存" width="100"></el-table-column>
                <el-table-column prop="number" label="货品数量" width="100">
                    <template #default="scope">
                        <el-input type="number"
                                  placeholder="请输入"
                                  v-model="scope.row.number"
                                  v-on:input="calculateMoney(scope.row)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="stkInrefp" label="进货单价" width="100">
                    <template #default="scope">
                        <el-input type="number"
                                  placeholder="请输入"
                                  v-model="scope.row.stkInrefp"
                                  v-on:input="calculateMoney(scope.row)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="money" label="金额" width="100"></el-table-column>
                <el-table-column prop="note" label="备注" width="150">
                    <template #default="scope">
                        <el-input placeholder="请输入" v-model="scope.row.note"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                    <template #default="scope">
                        <el-button link type="danger" size="small" v-on:click="del(scope.row)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: right; color: #606266; margin-top: 8px;">
                货品种类：{{ tableData.length }}
                货品数量：{{ calculateTotalNum }}
                总金额：{{ calculateTotalAmount }}
            </div>
        </div>

        <!-- 上传附件 -->
        <div class="form-group">
            <h3>上传附件</h3>
            <div class="upload-area">
                <el-upload action="/api/Upload"
                           :file-list.sync="fileList"
                           :on-success="handleUploadSuccess"
                           :before-upload="beforeUpload"
                           :limit="3">
                    <el-button type="primary">上传</el-button>
                </el-upload>
                <div class="tip">您可以上传 doc、pdf、rar 等格式的文件，单个文件上传最大 200MB。</div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div style="margin-top: 20px;">
            <el-button v-on:click="goBack">关闭</el-button>
            <el-button type="primary" v-on:click="saveAndAdd">保存并新增</el-button>
            <el-button type="primary" v-on:click="save">保存</el-button>
        </div>

        <!-- 货品选择模态框 -->
        <el-dialog title="添加货品" v-model="dialogVisible" width="800px">
            <el-form :inline="true" :model="goodsSearchForm" class="mb-4">
                <el-form-item label="货品编号/名称">
                    <el-input v-model="goodsSearchForm.goodsCodeName" placeholder="请输入货品编号/名称"></el-input>
                </el-form-item>
                <el-form-item label="单位" class="form-item">
                    <el-select v-model="goodsSearchForm.unit" placeholder="请选择" class="custom-unit-select">
                        <el-option v-for="item in unitOptions"
                                   :key="item.value"
                                   :label="item.dictLabel"
                                   :value="item.dictValue"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="queryGoods">查询</el-button>
                    <el-button v-on:click="resetGoodsForm">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="goodsTableData"
                      v-on:selection-change="val => selectedGoods = val">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="product_code" label="货品编号" width="120"></el-table-column>
                <el-table-column prop="product_name" label="货品名称" width="120"></el-table-column>
                <el-table-column prop="specification_model" label="规格型号" width="100"></el-table-column>
                <el-table-column prop="unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="inboundPrice" label="入库单价" width="100"></el-table-column>
                <el-table-column prop="currentInventory" label="当前库存" width="100"></el-table-column>
            </el-table>
            <el-pagination v-model:current-page="goodsCurrentPage"
                           v-model:page-size="goodsPageSize"
                           :page-sizes="[5, 10, 20, 50]"
                           :total="goodsTotal"
                           layout="total, sizes, prev, pager, next, jumper"
                           v-on:size-change="handleGoodsPageSizeChange"
                           v-on:current-change="handleGoodsCurrentPageChange"
                           style="margin-top: 16px; text-align: right;"></el-pagination>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="closeGoodsDialog">取消</el-button>
                    <el-button type="primary" v-on:click="confirmSelectGoods">确定</el-button>
                </div>
            </template>
    </div>

    <script>
        const { createApp, ref, reactive, computed, onMounted } = Vue;
        const app = createApp({
            setup() {
                // 基础表单数据
                const formData = reactive({
                    purchase_order_no: '',
                    purchase_date: '',
                    supplier_id: '',
                    contact_person: '',
                    contact_information: '',
                    purchasing_department: '',
                    purchaser: '',
                    note: '',
                    annex_code: ''
                });

                const generateLocationNumber = async () => {
                    try {
                        console.log("开始生成库位编号，使用rule_id=2");
                        const response = await axios.post(
                            '/NumberingRule/GenerateBusinessNumber',
                            { rule_id: 6 },  // 使用 rule_id=14，它对应 target_id=21
                            { headers: { 'Content-Type': 'application/json' } }
                        );
                        if (response.data.success) {
                            formData.purchase_order_no = response.data.businessNumber;
                            console.log("库位编号生成成功:", locationForm.locationNumber);
                        } else {
                            ElMessage.error(`库位编号生成失败：${response.data.message || '未知错误'}`);
                            locationForm.locationNumber = '';
                        }
                    } catch (error) {
                        console.error("生成库位编号异常:", error);
                        ElMessage.error('网络异常，无法生成库位编号，请重试');
                        locationForm.locationNumber = '';
                    }
                };

                // 供应商下拉框数据
                const supplierOptions = ref([]);

                // 上传文件列表
                const fileList = ref([]);

                // 进货明细表格数据
                const tableData = ref([]);

                // 计算总数量和总金额
                const calculateTotalNum = computed(() => {
                    return tableData.value.reduce((total, item) => {
                        return total + Number(item.number || 0);
                    }, 0);
                });
                const calculateTotalAmount = computed(() => {
                    return tableData.value.reduce((total, item) => {
                        return total + Number(item.money  || 0);
                    }, 0).toFixed(2);
                });

                // 计算单条金额
                const calculateMoney = (row) => {
                    const number = Number(row.number || 0);
                    const stkInrefp = Number(row.stkInrefp || 0);
                    row.money = (number * stkInrefp).toFixed(2);
                };

                // 货品选择模态框分页+搜索相关
                const dialogVisible = ref(false);
                const goodsSearchForm = reactive({
                    goodsCodeName: '',
                    unit: ''
                });
                const selectedGoods = ref([]);
                const goodsTableData = ref([]);
                const goodsCurrentPage = ref(1);
                const goodsPageSize = ref(10);
                const goodsTotal = ref(0);

                // 单位字典选项
                const unitOptions = ref([]);

                // 获取单位字典数据
                const getUnitDict = async () => {
                    try {
                        const response = await axios.get('/api/Dict/datas/Unit');
                        unitOptions.value = response.data;
                    } catch (error) {
                        console.error('获取单位字典失败：', error);
                        ElementPlus.ElMessage.error('获取单位数据失败，请稍后再试');
                    }
                };

                // 获取供应商列表（供下拉框使用）
                const getSupplierList = async () => {
                    try {
                        const response = await axios.get('/Supplier/GetSupplierList2');
                        if (response.data.success) {
                            console.log("供应商：")
                            console.log(response.data.data)
                            supplierOptions.value = response.data.data;
                        } else {
                            ElementPlus.ElMessage.error(response.data.message);
                        }
                    } catch (error) {
                        console.error('获取供应商列表失败：', error);
                        ElementPlus.ElMessage.error('网络异常，请稍后再试');
                    }
                };

                // 处理供应商选择变化（自动填充联系人和联系方式）
                const handleSupplierChange = async (supplierCode) => {
                    if (!supplierCode) {
                        formData.contact_person = '';
                        formData.contact_information = '';
                        return;
                    }
                    console.log(supplierCode)
                    try {
                        const response = await axios.get(`/api/Supplier/GetSupplierByIdDetail?code=${supplierCode}`);
                        if (response.data.success) {
                            const supplierDetail = response.data.data;
                            formData.contact_person = supplierDetail.contact_person || '';
                            formData.contact_information = supplierDetail.contact_phone_number || '';
                        } else {
                            ElementPlus.ElMessage.error(response.data.message);
                            formData.contact_person = '';
                            formData.contact_information = '';
                        }
                    } catch (error) {
                        console.error('获取供应商详情失败：', error);
                        ElementPlus.ElMessage.error('网络异常，请稍后再试');
                        formData.contact_person = '';
                        formData.contact_information = '';
                    }
                };

                // 供应商行业字典回显
                const getUnitDictValue = async (value) => {
                    try {
                        const response = await axios.get(`/api/Dict/label?dictTypeCode=Unit&dictValue=${value}`);
                        console.log('单位标签:', response.data);
                        return response.data;
                    } catch (error) {
                        console.error('获取单位失败：', error);
                        ElementPlus.ElMessage.error('获取单位失败，请稍后再试');
                        return value;
                    }
                };

                // 加载货品分页数据
                const loadGoodsData = async () => {
                    try {
                        const params = {
                            code: goodsSearchForm.goodsCodeName,
                            unit: goodsSearchForm.unit,
                            currentPage: goodsCurrentPage.value,
                            pageSize: goodsPageSize.value
                        };

                        const response = await axios.get('/PurchaseOrder/GetByCode', { params });

                        if (response.data.success) {
                            console.log(response.data.data)
                            let data = response.data.data;
                            for (let i = 0; i < data.length; i++) {
                                data[i].unit = await getUnitDictValue(data[i].unit);
                            }
                            console.log(data)
                            goodsTableData.value = data;
                            goodsTotal.value = response.data.total;
                        } else {
                            ElementPlus.ElMessage.error(response.data.message);
                        }
                    } catch (error) {
                        console.error('获取货品数据失败：', error);
                        ElementPlus.ElMessage.error('网络异常，请稍后再试');
                    }
                };
                
                // 货品查询按钮事件
                const queryGoods = () => {
                    goodsCurrentPage.value = 1;
                    loadGoodsData();
                };

                // 货品分页-每页条数变化
                const handleGoodsPageSizeChange = (newSize) => {
                    goodsPageSize.value = newSize;
                    goodsCurrentPage.value = 1;
                    loadGoodsData();
                };

                // 货品分页-页码变化
                const handleGoodsCurrentPageChange = (newPage) => {
                    goodsCurrentPage.value = newPage;
                    loadGoodsData();
                };

                // 重置货品查询表单
                const resetGoodsForm = () => {
                    goodsSearchForm.goodsCodeName = '';
                    goodsSearchForm.unit = '';
                    goodsCurrentPage.value = 1;
                    loadGoodsData();
                };

                // 打开货品选择模态框
                const openGoodsDialog = () => {
                    getUnitDict();
                    loadGoodsData();
                    dialogVisible.value = true;
                };

                // 关闭货品选择模态框
                const closeGoodsDialog = () => {
                    dialogVisible.value = false;
                };

                // 确认选择货品并添加到进货明细
                const confirmSelectGoods = async () => {
                    if (selectedGoods.value.length === 0) {
                        ElementPlus.ElMessage.warning('请选择至少一个货品');
                        return;
                    }
                    for (let item of selectedGoods.value) {

                        const unitLabel = await getUnitDictValue(item.unit);
                        const number = 1;
                        const stkInrefp = item.inboundPrice || 0;
                        const money = (number * stkInrefp).toFixed(2);
                        tableData.value.push({
                            productId: item.product_ID, // 新增：存储货品的主键Product_ID
                            product_name: item.product_name,
                            product_code: item.product_code,
                            specification_model: item.specification_model,
                            unit: item.unit,
                            type_of_goods: item.type_of_goods || '',
                            current_inventory: item.currentInventory || 0,
                            number: number,
                            stkInrefp: stkInrefp,
                            money: money,
                            note: ''
                        });
                    }
                    dialogVisible.value = false;
                };

                // 移除进货明细行
                const del = (row) => {
                    const index = tableData.value.findIndex(item => item.product_code === row.product_code);
                    if (index !== -1) {
                        tableData.value.splice(index, 1);
                    }
                };

                // 移除最后一行
                const removeGoodsRow = () => {
                    if (tableData.value.length > 0) {
                        tableData.value.pop();
                    } else {
                        ElementPlus.ElMessage.warning('没有可移除的货品');
                    }
                };

                        // 页面操作方法
                const goBack = () => { window.history.back(); };
                const saveAndAdd = () => {
                    ElementPlus.ElMessage.success('保存成功，即将跳转到新增页面');
                };
                const save = async () => {
                    // 1. 校验必填项
                    if (!formData.purchase_order_no || !formData.supplier_id || !formData.purchase_date || !formData.purchaser || tableData.value.length === 0) {
                        ElementPlus.ElMessage.warning('请填写完整必填项并添加货品明细');
                        return;
                    }

                    // 2. 构造请求体（与后端格式完全对齐）
                    const requestData = {
                        purchase_order_no: formData.purchase_order_no,
                        supplier_id: formData.supplier_id,
                        suppliers_id: formData.supplier_id,
                        purchase_date: formData.purchase_date.toISOString().split('T')[0],
                        contact_person: formData.contact_person,
                        contact_information: formData.contact_information,
                        purchaser: formData.purchaser,
                        organizations_id: formData.purchasing_department === '采购部' ? 1 : 2,
                        note: formData.note,
                        details: tableData.value.map(item => ({
                            Product_ID: item.productId,
                            purchase_unit_price: item.stkInrefp,
                            prod_num: item.number,
                            note: item.note
                        }))
                    };
                    
                    console.log(tableData.value)
                    console.log(requestData)

                            

                    // 3. 调用后端新增接口
                    try {
                        const response = await axios.post(
                            '/api/PurchaseOrder/Add',
                            JSON.stringify(requestData), // 必须序列化
                            {
                                headers: {
                                    'Content-Type': 'application/json' // 明确指定格式
                                }
                            }
                        );
                        if (response.data.success) {
                            ElementPlus.ElMessage.success('保存成功');
                            goBack();
                        } else {
                            ElementPlus.ElMessage.error(response.data.message || '保存失败');
                        }
                    } catch (error) {
                        console.error('保存失败', error);
                        ElementPlus.ElMessage.error('网络异常，请稍后再试');
                    }
                };

                // 附件上传校验
                const beforeUpload = (file) => {
                    const allowedTypes = ['application/msword', 'application/pdf', 'application/x-rar-compressed'];
                    const maxSize = 200 * 1024 * 1024;
                    if (!allowedTypes.includes(file.type)) {
                        ElementPlus.ElMessage.error('仅支持 doc、pdf、rar 格式文件');
                        return false;
                    }
                    if (file.size > maxSize) {
                        ElementPlus.ElMessage.error('单个文件最大不能超过200MB');
                        return false;
                    }
                    return true;    
                };

                const handleUploadSuccess = (response) => {
                    if (response.success) {
                        formData.annex_code = response.data.annex_code;
                        ElementPlus.ElMessage.success('附件上传成功');
                    } else {
                        ElementPlus.ElMessage.error('附件上传失败：' + response.message);
                    }
                };

                onMounted(() => {
                    getSupplierList(); // 页面加载时获取供应商数据
                    generateLocationNumber()
                });

                return {
                    formData,
                    fileList,
                    tableData,
                    calculateTotalNum,
                    calculateTotalAmount,
                    calculateMoney,
                    dialogVisible,
                    goodsSearchForm,
                    selectedGoods,
                    goodsTableData,
                    openGoodsDialog,
                    closeGoodsDialog,
                    queryGoods,
                    resetGoodsForm,
                    confirmSelectGoods,
                    del,
                    removeGoodsRow,
                    goBack,
                    saveAndAdd,
                    save,
                    beforeUpload,
                    handleUploadSuccess,
                    unitOptions,
                    goodsCurrentPage,
                    goodsPageSize,
                    goodsTotal,
                    handleGoodsPageSizeChange,
                    handleGoodsCurrentPageChange,
                    supplierOptions,
                    handleSupplierChange
                };
            }
        });
        app.use(ElementPlus);
        app.mount('.container');
    </script>
</body>
</html>